import React, { Component } from 'react'
import request from '../util/request'

export default class Registry extends Component {
    state = {
        phone:'',
        password:'',
        role:'v2'
    }
    render() {
        let {phone,password,role} = this.state;
        return (
            <div>
                手机号：<input type="text" placeholder="手机号 " value={phone} name="phone" onChange={this.change}></input>
                密码：<input type="text" placeholder="密码" value={password} name="password" onChange={this.change}></input>
                身份：<input type="text" value={role} name="role" onChange={this.change}/>
                <button onClick={this.registry}>注册</button>
            </div>
        )
    }

    //受控表单
    change = (e) => {
        this.setState({
            [e.target.name]:e.target.value
        })
    }

    //注册
    registry = () => {
        //容错处理
        let {phone,password,role} = this.state;
        if(/^\d{11}$/.test(phone) &&password && role){
            //注册接口
            request.post('/api/registry',{phone,password,role}).then(res => {
                if(res.code === 1){
                    alert("注册成功");
                    this.props.history.push('/login');
                }else{
                    alert("注册失败")
                }
            })
        }else{
            alert("参数不完整")
        }
    }
}
